/**
 * @name ActicleEdit
 * @description 文章编辑页面
 * @author darcrand
 */

import React, { useState, useRef, useMemo, useCallback } from 'react'
import { Divider, Button, Modal } from 'antd'
import { useSetState, useSize } from 'ahooks'

import MarkdownEditor from '@/components-bussiness/MarkdownEditor'
import styles from './styles.module.less'

const ActicleEdit = () => {
  // 用于平铺整个页面
  const refTools = useRef(null)
  const toolSize = useSize(refTools)
  const viewSize = useSize(window.document.documentElement)
  const editorHeight = useMemo(() => {
    if (toolSize.height && viewSize.height) {
      return viewSize.height - toolSize.height
    } else {
      return '50vh'
    }
  }, [toolSize.height, viewSize.height])

  // 表单部分
  const [form, setForm] = useSetState({
    title: '',
    category: '',
  })
  const onTitleChange = useCallback((e) => {
    const title = e?.target?.value ?? ''
    setForm({ title })
  }, [])

  // 文本内容
  const [content, setContent] = useState('')

  // 发布用的弹框
  const [visibleModal, setVisible] = useState(false)
  const openModal = useCallback(() => {
    setVisible(true)
  }, [])
  const onCancel = useCallback(() => {
    setVisible(false)
  }, [])
  const onConfirmToPublish = useCallback(() => {
    console.log('ok', { content, form })
    console.log(JSON.stringify({ content }))
    setVisible(false)
  }, [content, form])

  return (
    <>
      <div ref={refTools} className={styles.top_tools}>
        <section className={styles.input_wrapper}>
          <input
            placeholder='请输入文章标题'
            className={styles.input_title}
            maxLength={50}
            value={form.title}
            onChange={onTitleChange}
          />
        </section>
        <Divider type='vertical' />
        <Button.Group>
          <Button type='primary' ghost>
            保存草稿
          </Button>
          <Button type='primary' onClick={openModal}>
            立即发布
          </Button>
        </Button.Group>
      </div>

      <MarkdownEditor value={content} onChange={setContent} height={editorHeight} />

      <Modal visible={visibleModal} title='发布文章' onCancel={onCancel} onOk={onConfirmToPublish}>
        <p>分类</p>
      </Modal>
    </>
  )
}

export default React.memo(ActicleEdit)
